package com.cyx.spring.mvc;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.StrUtil;
import com.cyx.spring.context.AnnotationConfigApplicationContext;
import com.cyx.spring.context.ApplicationContext;
import com.cyx.spring.io.PropertyResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * ContextLoaderListener
 *
 * @author yongxiang
 * @date 2024/10/28 10:07
 * @desc
 */


public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //初始化容器
        try {
            createApplicationContext(sce);
        } catch (Exception e) {
            throw new RuntimeException("初始化容器失败。。",e);
        }
        ServletContext servletContext = sce.getServletContext();
        //添加前端控制器
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        ServletRegistration.Dynamic dispatcherServlet1 = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dispatcherServlet1.addMapping("/");
        dispatcherServlet1.setLoadOnStartup(0);

    }

    private void createApplicationContext(ServletContextEvent sce) throws Exception {
        //获取参数
        ServletContext servletContext = sce.getServletContext();
        String configuration = servletContext.getInitParameter("configuration");
        if (StrUtil.isNotBlank(configuration)){
            String propertiesConfig = servletContext.getInitParameter("properties");
            if(StrUtil.isBlank(propertiesConfig)){
                propertiesConfig = "application.properties";
            }
            Properties properties = new Properties();
            properties.load(new ClassPathResource(propertiesConfig).getReader(Charset.defaultCharset()));
            new AnnotationConfigApplicationContext(Class.forName(configuration),new PropertyResolver(properties));
        }
    }
}
